package br.com.grupo01.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.grupo01.managedBeam.LoginMB;


@WebFilter(servletNames={"Faces Servlet"})
public class AccessControl implements Filter {
		
	public void init(FilterConfig filterConfig) throws ServletException {}
	
	public void destroy(){}	

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		
		LoginMB loginMB = (LoginMB)session.getAttribute("loginMB");
		
		boolean precisaAutenticar = true;
		
		//System.out.println("loginMB existe: " +  (loginMB != null));
		
		if (loginMB != null)
			if (loginMB.getUsuarioLogado())
				precisaAutenticar = false;
		
		if ( !precisaAutenticar || req.getRequestURI().endsWith("login.xhtml") ) {
			chain.doFilter(request, response);			
		}
		else {
			HttpServletResponse res = (HttpServletResponse) response;
			res.sendRedirect("login.xhtml");
		}
			
						
	}
	
}
